<template>
    <a-row>
        <a-col flex="450px">
            <a-card :style="{ width: '450px' }" title="菜单列表">
                <template #extra>
                    <a-button-group>
                        <a-button @click="loadTree()" title="刷新">
                            <template #icon>
                                <icon-refresh />
                            </template>
                        </a-button>
                        <a-button @click="openEditModal()" title="新增菜单">
                            <template #icon>
                                <icon-plus />
                            </template>
                        </a-button>
                        <!-- <a-popconfirm :content="$t('common.deleteTreeTip')" @ok="remove">
                            <a-button status="danger" >
                                <template #icon>
                                    <icon-delete />
                                </template>
                            </a-button>
                        </a-popconfirm> -->
                    </a-button-group>
                </template>
                <a-tree ref="treeRef" v-model:checked-keys="checkedKeys" :checkable="false"
                    v-model:expanded-keys="expandedKeys" @expand="onExpand" :data="treeData" check-strictly
                    v-model:selected-keys="selectedKeys" @select="onSelect" :field-names="fieldNames">
                    <template #icon="{ node }">
                        <component v-if="node.icon" :is="node.icon"></component>
                    </template>
                    <template #extra="node">
                        <a-button-group
                            style="position: absolute; right: 16px; font-size: 12px;  background-color: transparent">
                            <a-button class="bgtransparent" @click="addChild(node)" title="新增菜单">
                                <icon-plus />
                            </a-button>
                            <a-popconfirm :content="$t('common.deleteTreeTip')" @ok="remove(node)">
                                <a-button status="danger" class="bgtransparent" title="删除菜单">
                                    <icon-delete />
                                </a-button>
                            </a-popconfirm>
                        </a-button-group>
                    </template>
                </a-tree>
            </a-card>
        </a-col>
        <a-col flex="1" class="menu-item" v-if="visiable">
            <a-card title="菜单操作">
                <a-form :model="dataForm" ref="dataFormRef" :rules="dataFormRules" @submit="handleSubmit">
                    <a-form-item field="parentId" :label="$t('menu.columns.parentId')">
                        <a-tree-select v-model="dataForm.parentId" allow-clear :data="treeOption"
                            :field-names="{ icon: () => { } }"
                            :placeholder="$t('common.selectPlaceholder') + $t('menu.columns.parentId')">
                            <template #tree-slot-icon="{ node }">
                                <!-- {{ node.iconStr }} -->
                                <component v-if="node.iconStr" :is="node.iconStr"></component>
                            </template>
                        </a-tree-select>
                    </a-form-item>
                    <a-form-item field="type" :label="$t('menu.columns.type')">
                        <a-select v-model="dataForm.type" allow-clear :options="typeOptions"
                            :placeholder="$t('common.selectPlaceholder') + $t('menu.columns.type')" />
                    </a-form-item>
                    <a-form-item field="title" :label="$t('menu.columns.title')">
                        <a-input v-model="dataForm.title"
                            :placeholder="$t('common.inputPlaceholder') + $t('menu.columns.title')" />
                    </a-form-item>
                    <a-form-item field="code" :label="$t('menu.columns.code')">
                        <a-input v-model="dataForm.code"
                            :placeholder="$t('common.inputPlaceholder') + $t('menu.columns.code')" />
                    </a-form-item>
                    <a-form-item field="sortNo" :label="$t('menu.columns.sortNo')">
                        <a-input v-model="dataForm.sortNo"
                            :placeholder="$t('common.inputPlaceholder') + $t('menu.columns.sortNo')" />
                    </a-form-item>
                    <a-form-item field="icon" :label="$t('menu.columns.icon')">
                        <a-select v-model="dataForm.icon" allow-clear allow-search
                            :placeholder="$t('common.selectPlaceholder') + $t('menu.columns.icon')">
                            <template #label="{ data }">
                                <component :is="data.value" /><span style="margin-left: 20px">{{ data.value }}</span>
                            </template>
                            <a-option :value="item.value" v-for="item in iconOptions" :key="item.value">
                                <component :is="item.value" /><span style="margin-left: 20px">{{ item.value }}</span>
                            </a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item field="path" :label="$t('menu.columns.path')">
                        <a-input v-model="dataForm.path"
                            :placeholder="$t('common.inputPlaceholder') + $t('menu.columns.path')" />
                    </a-form-item>
                    <a-form-item v-if="dataForm.type === '0'" field="component" :label="$t('menu.columns.component')">
                        <a-select v-model="dataForm.component"
                            :placeholder="$t('common.inputPlaceholder') + $t('menu.columns.component')">
                            <a-option value="Layout">Layout</a-option>
                            <a-option value="PageView">PageView</a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item v-else field="component" :label="$t('menu.columns.component')">
                        <a-input v-model="dataForm.component"
                            :placeholder="$t('common.inputPlaceholder') + $t('menu.columns.component')" />
                    </a-form-item>
                    <a-form-item field="redirectUrl" :label="$t('menu.columns.redirectUrl')">
                        <a-input v-model="dataForm.redirectUrl"
                            :placeholder="$t('common.inputPlaceholder') + $t('menu.columns.redirectUrl')" />
                    </a-form-item>
                    <a-form-item field="hidden" :label="$t('menu.columns.hidden')">
                        <a-radio-group v-model="dataForm.hidden"
                            :placeholder="$t('common.selectPlaceholder') + $t('menu.columns.hidden')">
                            <a-radio :value="false">显示</a-radio>
                            <a-radio :value="true">隐藏</a-radio>
                        </a-radio-group>
                    </a-form-item>
                    <a-form-item field="activeMenu" :label="$t('menu.columns.activeMenu')">
                        <a-tree-select v-model="dataForm.activeMenu" allow-clear :data="treeOption"
                            :field-names="{ icon: () => { } }"
                            :placeholder="$t('common.selectPlaceholder') + $t('menu.columns.activeMenu')">
                            <template #tree-slot-icon="{ node }">
                                <component v-if="node.iconStr" :is="node.iconStr"></component>
                            </template>
                        </a-tree-select>
                    </a-form-item>
                    <a-form-item field="status" :label="$t('menu.columns.status')">
                        <a-switch v-model="dataForm.status" :default-checked="true" :checked-value="1"
                            :unchecked-value="0"></a-switch>
                    </a-form-item>
                    <a-form-item>
                        <a-button html-type="submit" type="primary">保存</a-button>
                        <a-button @click="() => { visiable = false }">取消</a-button>
                    </a-form-item>
                </a-form>
            </a-card>

        </a-col>
    </a-row>
</template>
<script setup>
import { Message } from '@arco-design/web-vue'
import { list, show, save, del } from '@/api/menu.js'
import { useI18n } from 'vue-i18n';
import { reactive, ref, onMounted } from 'vue';
import { iconOptions } from '@/config/constants';

const { t } = useI18n()
// 树形菜单
const treeData = ref([])
const treeOption = ref([])
const treeRef = ref()
const loading = ref(false)
const checkedKeys = ref([])
const selectedKeys = ref([]);
const expandedKeys = ref([])
const visiable = ref(false)
const fieldNames = reactive({
    key: 'id',
    icon: () => { }
})

const onExpand = (newExpandedKeys) => {
    expandedKeys.value = newExpandedKeys
}

const onSelect = (selectedKeys) => {
    openEditModal(selectedKeys[0])
}
const expandAll = (menus) => {
    let expandedKeys = []
    menus.forEach(element => {
        if (element.type !== 2) {
            expandedKeys.push(element.id)
        }
        if (element.children && element.children.length > 0) {
            expandedKeys = expandedKeys.concat(expandAll(element.children))
        }
    });
    return expandedKeys
}

const transferOption = (menus) => {
    let treeOption = []
    menus.forEach(element => {
        let data = {
            key: element.id,
            iconStr: element.icon,
            icon: () => { },
            title: element.title,
            children: []
        }
        if (element.children && element.children.length > 0) {
            data.children = transferOption(element.children)
        }
        treeOption.push(data)
    });
    return treeOption
}

const handleSubmit = ({ errors }) => {
    if (!errors) {
        save(dataForm.value).then(res => {
            if (res.code === 200) {
                Message.success(t('common.operateSuccess'))
                visiable.value = false
                loadTree()
            } else {
                Message.error(res.message)
            }
        })
    }
}

const loadTree = () => {
    loading.value = true
    list({}).then(res => {
        if (res.code === 200) {
            loading.value = false
            treeData.value = res.data
            expandedKeys.value = expandAll(treeData.value)
            treeOption.value = transferOption(treeData.value)
        } else {
            Message.error(res.message)
        }
    })
}

const addChild = (item) => {
    console.log(item)
    dataForm.value = {
        type: '1',
        parentId: item.id,
        hidden: false,
        status: 1
    }
    dataFormTitle.value = t('common.add')
    visiable.value = true
}

const openEditModal = (item) => {
    if (item) {
        show({ id: item }).then(res => {
            if (res.code === 200) {
                res.data.type = res.data.type.toString()
                dataForm.value = res.data
            } else {
                Message.error(res.message)
            }
        })
        dataFormTitle.value = t('common.edit')
    } else {
        dataForm.value = {
            hidden: false,
            status: 1
        }
        dataFormTitle.value = t('common.add')
    }
    visiable.value = true
}

const remove = (item) => {
    let deleteIds = []
    if (item) {
        // 单个删除
        deleteIds.push(item.id)
    } else {
        deleteIds = [...checkedKeys.value]
    }
    if (deleteIds.length === 0) {
        Message.warning(t('common.chooseDeleteItem'))
        return
    }
    del({ ids: deleteIds }).then(res => {
        if (res.code === 200) {
            Message.success(t('common.operateSuccess'))
            loadTree()
        } else {
            Message.error(res.message)
        }
    })
}

onMounted(() => {
    loadTree()
})

const typeOptions = [
    {
        label: '目录',
        value: '0'
    },
    {
        label: '菜单',
        value: '1'
    },
    {
        label: '按钮',
        value: '2'
    }
]


let dataForm = ref({

})
const dataFormRef = ref()
const dataFormTitle = ref('')
const dataFormRules = {
    title: [
        {
            required: true,
            message: t('common.inputPlaceholder') + t('menu.columns.title'),
        },
    ],
    code: [
        {
            required: true,
            message: t('common.inputPlaceholder') + t('menu.columns.code'),
        },
    ],
    type: [
        {
            required: true,
            message: t('common.selectPlaceholder') + t('menu.columns.type'),
        },
    ],

}

</script>
<style lang="less" scoped>
.arco-tree {
    height: calc(100vh - 240px);
    overflow-y: auto;

    .bgtransparent {
        background-color: transparent;
    }
}

.menu-item {
    margin-left: 100px;
    max-width: 800px;

    .arco-form-item {
        margin-bottom: 20px;

    }
}
</style>